import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
import { Progress } from './ui/progress';
import { StopCircle, Clock, Trophy, Star, Target } from 'lucide-react';
import { motion, AnimatePresence } from 'motion/react';
import { TestResult } from '../types';

interface InhibitoryControlTestProps {
  onComplete: (result: TestResult) => void;
}

interface Trial {
  id: number;
  word: string;
  color: string;
  condition: 'congruent' | 'incongruent' | 'neutral';
  correctResponse: string;
}

const COLORS = ['红色', '蓝色', '绿色', '黄色'];
const COLOR_MAP = {
  '红色': 'text-red-500',
  '蓝色': 'text-blue-500',
  '绿色': 'text-green-500',
  '黄色': 'text-yellow-500'
};

const NEUTRAL_WORDS = ['星星', '房子', '桌子', '花朵'];

export function InhibitoryControlTest({ onComplete }: InhibitoryControlTestProps) {
  const [stage, setStage] = useState<'instructions' | 'practice' | 'test' | 'results'>('instructions');
  const [currentTrial, setCurrentTrial] = useState(0);
  const [trials, setTrials] = useState<Trial[]>([]);
  const [responses, setResponses] = useState<string[]>([]);
  const [reactionTimes, setReactionTimes] = useState<number[]>([]);
  const [accuracy, setAccuracy] = useState<boolean[]>([]);
  const [timeLeft, setTimeLeft] = useState(360); // 6分钟
  const [startTime, setStartTime] = useState<number>(0);
  const [trialStartTime, setTrialStartTime] = useState<number>(0);
  const [score, setScore] = useState(0);
  const [isPractice, setIsPractice] = useState(false);

  const PRACTICE_TRIALS = 12;
  const TEST_TRIALS = 72;

  const generateTrials = (count: number): Trial[] => {
    const newTrials: Trial[] = [];
    const conditionsPerBlock = Math.floor(count / 3);
    
    // 生成一致条件试次
    for (let i = 0; i < conditionsPerBlock; i++) {
      const color = COLORS[Math.floor(Math.random() * COLORS.length)];
      newTrials.push({
        id: newTrials.length + 1,
        word: color,
        color: color,
        condition: 'congruent',
        correctResponse: color
      });
    }
    
    // 生成不一致条件试次
    for (let i = 0; i < conditionsPerBlock; i++) {
      const wordColor = COLORS[Math.floor(Math.random() * COLORS.length)];
      let displayColor = COLORS[Math.floor(Math.random() * COLORS.length)];
      while (displayColor === wordColor) {
        displayColor = COLORS[Math.floor(Math.random() * COLORS.length)];
      }
      
      newTrials.push({
        id: newTrials.length + 1,
        word: wordColor,
        color: displayColor,
        condition: 'incongruent',
        correctResponse: displayColor
      });
    }
    
    // 生成中性条件试次
    for (let i = 0; i < count - conditionsPerBlock * 2; i++) {
      const word = NEUTRAL_WORDS[Math.floor(Math.random() * NEUTRAL_WORDS.length)];
      const color = COLORS[Math.floor(Math.random() * COLORS.length)];
      newTrials.push({
        id: newTrials.length + 1,
        word: word,
        color: color,
        condition: 'neutral',
        correctResponse: color
      });
    }
    
    // 打乱试次顺序
    for (let i = newTrials.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [newTrials[i], newTrials[j]] = [newTrials[j], newTrials[i]];
    }
    
    return newTrials;
  };

  useEffect(() => {
    let interval: NodeJS.Timeout;
    if (stage === 'test' && timeLeft > 0) {
      interval = setInterval(() => {
        setTimeLeft(prev => {
          if (prev <= 1) {
            setStage('results');
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    }
    return () => clearInterval(interval);
  }, [stage, timeLeft]);

  const handleStartPractice = () => {
    setStage('practice');
    setIsPractice(true);
    const practiceTrials = generateTrials(PRACTICE_TRIALS);
    setTrials(practiceTrials);
    setCurrentTrial(0);
    setTrialStartTime(Date.now());
  };

  const handleStartTest = () => {
    setStage('test');
    setIsPractice(false);
    setStartTime(Date.now());
    const testTrials = generateTrials(TEST_TRIALS);
    setTrials(testTrials);
    setCurrentTrial(0);
    setResponses([]);
    setReactionTimes([]);
    setAccuracy([]);
    setScore(0);
    setTrialStartTime(Date.now());
  };

  const handleColorResponse = (selectedColor: string) => {
    const reactionTime = Date.now() - trialStartTime;
    const trial = trials[currentTrial];
    const correct = selectedColor === trial.correctResponse;
    
    if (!isPractice) {
      setResponses(prev => [...prev, selectedColor]);
      setReactionTimes(prev => [...prev, reactionTime]);
      setAccuracy(prev => [...prev, correct]);
      
      if (correct) {
        setScore(prev => prev + 1);
      }
    }

    // 下一个试次
    if (currentTrial < trials.length - 1) {
      setCurrentTrial(prev => prev + 1);
      setTrialStartTime(Date.now());
    } else {
      if (isPractice) {
        // 练习结束，开始正式测试
        handleStartTest();
      } else {
        // 测试结束
        setStage('results');
      }
    }
  };

  const handleComplete = () => {
    const totalCorrect = accuracy.filter(a => a).length;
    const overallAccuracy = Math.round((totalCorrect / accuracy.length) * 100);
    
    // 计算不同条件的表现
    const congruentTrials = trials.filter(t => t.condition === 'congruent');
    const incongruentTrials = trials.filter(t => t.condition === 'incongruent');
    
    const congruentAccuracy = congruentTrials.length > 0 ? 
      Math.round((accuracy.filter((a, i) => trials[i].condition === 'congruent' && a).length / congruentTrials.length) * 100) : 0;
    
    const incongruentAccuracy = incongruentTrials.length > 0 ?
      Math.round((accuracy.filter((a, i) => trials[i].condition === 'incongruent' && a).length / incongruentTrials.length) * 100) : 0;

    // 计算Stroop效应（不一致条件与一致条件的反应时差异）
    const congruentRTs = reactionTimes.filter((rt, i) => trials[i].condition === 'congruent');
    const incongruentRTs = reactionTimes.filter((rt, i) => trials[i].condition === 'incongruent');
    
    const avgCongruentRT = congruentRTs.length > 0 ? 
      Math.round(congruentRTs.reduce((sum, rt) => sum + rt, 0) / congruentRTs.length) : 0;
    
    const avgIncongruentRT = incongruentRTs.length > 0 ?
      Math.round(incongruentRTs.reduce((sum, rt) => sum + rt, 0) / incongruentRTs.length) : 0;
    
    const stroopEffect = avgIncongruentRT - avgCongruentRT;
    
    // 抑制控制得分：准确率越高、Stroop效应越小得分越高
    const inhibitionScore = Math.max(0, Math.min(100, 
      Math.round(overallAccuracy - (stroopEffect / 10))
    ));

    const timeUsed = Math.round((Date.now() - startTime) / 1000);

    const result: TestResult = {
      id: Date.now().toString(),
      testType: 'inhibitory-control',
      score: inhibitionScore,
      completedAt: new Date(),
      duration: timeUsed,
      details: {
        totalTrials: trials.length,
        correctResponses: totalCorrect,
        overallAccuracy,
        congruentAccuracy,
        incongruentAccuracy,
        stroopEffect,
        averageReactionTime: Math.round(reactionTimes.reduce((sum, rt) => sum + rt, 0) / reactionTimes.length),
        inhibitionIndex: Math.round(100 - (stroopEffect / 10))
      }
    };

    onComplete(result);
  };

  if (stage === 'instructions') {
    return (
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="max-w-2xl mx-auto"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-red-200 shadow-lg">
          <CardHeader className="text-center pb-8">
            <div className="w-16 h-16 bg-gradient-to-br from-red-600 to-rose-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
              <StopCircle className="w-8 h-8 text-white" />
            </div>
            <CardTitle className="text-2xl text-slate-800">抑制控制测试</CardTitle>
            <p className="text-slate-600 mt-2">测试您的自控力和注意力控制能力</p>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="bg-gradient-to-r from-red-50 to-rose-50 rounded-xl p-6 border border-red-100">
              <h3 className="font-semibold text-red-900 mb-4 flex items-center gap-2">
                <Star className="w-5 h-5" />
                测试说明
              </h3>
              <div className="space-y-3 text-slate-700">
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-red-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">1</span>
                  <p>您将看到不同颜色显示的词语</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-red-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">2</span>
                  <p><strong>忽略词语内容</strong>，只关注词语的显示颜色</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-red-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">3</span>
                  <p>快速准确地点击对应的颜色按钮</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-red-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">4</span>
                  <p>例如：看到红色的"蓝色"，应该选择红色</p>
                </div>
              </div>
            </div>

            {/* 示例 */}
            <div className="bg-slate-50 rounded-xl p-4 border border-slate-200">
              <h4 className="font-semibold text-slate-700 mb-3 text-center">示例</h4>
              <div className="flex justify-center items-center gap-8">
                <div className="text-center">
                  <div className="text-3xl font-bold text-blue-500 mb-2">红色</div>
                  <div className="text-sm text-slate-600">词语内容：红色</div>
                  <div className="text-sm text-slate-600">显示颜色：蓝色</div>
                  <div className="text-sm font-semibold text-blue-600 mt-1">→ 选择蓝色</div>
                </div>
                <Target className="w-6 h-6 text-slate-400" />
                <div className="text-center">
                  <div className="text-3xl font-bold text-green-500 mb-2">绿色</div>
                  <div className="text-sm text-slate-600">词语内容：绿色</div>
                  <div className="text-sm text-slate-600">显示颜色：绿色</div>
                  <div className="text-sm font-semibold text-green-600 mt-1">→ 选择绿色</div>
                </div>
              </div>
            </div>

            <div className="grid md:grid-cols-3 gap-4">
              <div className="text-center p-4 bg-gradient-to-br from-red-50 to-red-100 rounded-xl border border-red-200">
                <div className="text-2xl font-bold text-red-600 mb-1">72</div>
                <div className="text-sm text-red-700">测试试次</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-rose-50 to-rose-100 rounded-xl border border-rose-200">
                <div className="text-2xl font-bold text-rose-600 mb-1">6</div>
                <div className="text-sm text-rose-700">分钟限时</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-red-50 to-rose-50 rounded-xl border border-red-200">
                <div className="text-2xl font-bold text-slate-600 mb-1">12</div>
                <div className="text-sm text-slate-700">练习试次</div>
              </div>
            </div>

            <Button 
              onClick={handleStartPractice}
              className="w-full bg-gradient-to-r from-red-600 to-rose-500 hover:from-red-700 hover:to-rose-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
              size="lg"
            >
              开始练习
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  if (stage === 'practice' || stage === 'test') {
    const trial = trials[currentTrial];
    const progress = (currentTrial / trials.length) * 100;

    if (!trial) return null;

    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-4xl mx-auto space-y-6"
      >
        {/* 顶部状态栏 */}
        <div className="flex flex-col sm:flex-row gap-4 items-center justify-between">
          <div className="flex items-center gap-4">
            <Badge variant="outline" className="bg-red-100 text-red-700 border-red-300">
              {isPractice ? '练习' : '测试'} {currentTrial + 1} / {trials.length}
            </Badge>
            <Badge variant="outline" className={`${
              trial.condition === 'congruent' ? 'bg-green-100 text-green-700 border-green-300' :
              trial.condition === 'incongruent' ? 'bg-orange-100 text-orange-700 border-orange-300' :
              'bg-blue-100 text-blue-700 border-blue-300'
            }`}>
              {trial.condition === 'congruent' ? '一致条件' :
               trial.condition === 'incongruent' ? '不一致条件' : '中性条件'}
            </Badge>
            {!isPractice && (
              <div className="flex items-center gap-2 text-slate-600">
                <Trophy className="w-4 h-4" />
                <span className="font-semibold">{score} / {currentTrial}</span>
              </div>
            )}
          </div>
          
          {stage === 'test' && (
            <div className="flex items-center gap-2">
              <Clock className="w-4 h-4 text-slate-500" />
              <span className={`font-mono text-lg font-bold ${timeLeft <= 60 ? 'text-red-500' : 'text-slate-700'}`}>
                {Math.floor(timeLeft / 60)}:{(timeLeft % 60).toString().padStart(2, '0')}
              </span>
            </div>
          )}
        </div>

        <Progress value={progress} className="h-2" />

        {/* 指令提醒 */}
        <Card className="bg-gradient-to-r from-red-50 to-rose-50 border-red-200">
          <CardContent className="py-4">
            <div className="text-center">
              <h3 className="text-lg font-semibold text-red-800">
                请选择词语的显示颜色，忽略词语内容
              </h3>
            </div>
          </CardContent>
        </Card>

        {/* 测试区域 */}
        <Card className="bg-white/90 backdrop-blur-sm border-red-200 shadow-lg">
          <CardContent className="py-16">
            <div className="text-center space-y-12">
              <motion.div
                key={trial.id}
                initial={{ scale: 0.8, opacity: 0 }}
                animate={{ scale: 1, opacity: 1 }}
                transition={{ duration: 0.3 }}
                className="mb-8"
              >
                <div className={`text-6xl font-bold ${COLOR_MAP[trial.color as keyof typeof COLOR_MAP]} drop-shadow-lg`}>
                  {trial.word}
                </div>
              </motion.div>
              
              <div className="grid grid-cols-2 sm:grid-cols-4 gap-4 max-w-2xl mx-auto">
                {COLORS.map((color) => (
                  <Button
                    key={color}
                    onClick={() => handleColorResponse(color)}
                    className={`h-16 text-lg font-semibold shadow-lg transition-all duration-200 ${
                      color === '红色' ? 'bg-red-500 hover:bg-red-600 text-white' :
                      color === '蓝色' ? 'bg-blue-500 hover:bg-blue-600 text-white' :
                      color === '绿色' ? 'bg-green-500 hover:bg-green-600 text-white' :
                      'bg-yellow-500 hover:bg-yellow-600 text-white'
                    }`}
                  >
                    {color}
                  </Button>
                ))}
              </div>
            </div>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  if (stage === 'results') {
    const totalCorrect = accuracy.filter(a => a).length;
    const overallAccuracy = Math.round((totalCorrect / accuracy.length) * 100);
    
    const congruentTrials = trials.filter(t => t.condition === 'congruent');
    const incongruentTrials = trials.filter(t => t.condition === 'incongruent');
    
    const congruentAccuracy = congruentTrials.length > 0 ? 
      Math.round((accuracy.filter((a, i) => trials[i].condition === 'congruent' && a).length / congruentTrials.length) * 100) : 0;
    
    const incongruentAccuracy = incongruentTrials.length > 0 ?
      Math.round((accuracy.filter((a, i) => trials[i].condition === 'incongruent' && a).length / incongruentTrials.length) * 100) : 0;

    const congruentRTs = reactionTimes.filter((rt, i) => trials[i].condition === 'congruent');
    const incongruentRTs = reactionTimes.filter((rt, i) => trials[i].condition === 'incongruent');
    
    const avgCongruentRT = congruentRTs.length > 0 ? 
      Math.round(congruentRTs.reduce((sum, rt) => sum + rt, 0) / congruentRTs.length) : 0;
    
    const avgIncongruentRT = incongruentRTs.length > 0 ?
      Math.round(incongruentRTs.reduce((sum, rt) => sum + rt, 0) / incongruentRTs.length) : 0;
    
    const stroopEffect = avgIncongruentRT - avgCongruentRT;
    const inhibitionScore = Math.max(0, Math.min(100, 
      Math.round(overallAccuracy - (stroopEffect / 10))
    ));

    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-2xl mx-auto"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-red-200 shadow-xl">
          <CardHeader className="text-center pb-6">
            <motion.div
              initial={{ scale: 0 }}
              animate={{ scale: 1 }}
              transition={{ delay: 0.2, type: "spring", stiffness: 200 }}
              className="w-20 h-20 bg-gradient-to-br from-red-600 to-rose-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg"
            >
              <Trophy className="w-10 h-10 text-white" />
            </motion.div>
            
            <CardTitle className="text-3xl text-slate-800 mb-2">测试完成！</CardTitle>
            <div className="text-6xl font-bold bg-gradient-to-r from-red-600 to-rose-500 bg-clip-text text-transparent">
              {inhibitionScore}
            </div>
            <p className="text-slate-600">抑制控制能力得分</p>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="grid grid-cols-2 gap-4">
              <div className="text-center p-4 bg-gradient-to-br from-red-50 to-red-100 rounded-xl border border-red-200">
                <div className="text-2xl font-bold text-red-600 mb-1">{overallAccuracy}%</div>
                <div className="text-sm text-red-700">总准确率</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-rose-50 to-rose-100 rounded-xl border border-rose-200">
                <div className="text-2xl font-bold text-rose-600 mb-1">{stroopEffect}ms</div>
                <div className="text-sm text-rose-700">Stroop效应</div>
              </div>
            </div>

            <div className="space-y-3">
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">一致条件准确率</span>
                <span className="font-semibold text-slate-800">{congruentAccuracy}%</span>
              </div>
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">不一致条件准确率</span>
                <span className="font-semibold text-slate-800">{incongruentAccuracy}%</span>
              </div>
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">抑制控制指数</span>
                <span className="font-semibold text-slate-800">{Math.round(100 - (stroopEffect / 10))}%</span>
              </div>
            </div>

            <Button 
              onClick={handleComplete}
              className="w-full bg-gradient-to-r from-red-600 to-rose-500 hover:from-red-700 hover:to-rose-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
              size="lg"
            >
              查看详细结果
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  return null;
}